package org.gpf.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class LoginFilter implements Filter {

	private String noLoginPath;
	
	@Override
	public void destroy() {
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest req = (HttpServletRequest) request;
		HttpSession session = req.getSession();
		
		if (session.getAttribute("username") != null) {
			chain.doFilter(request, response);
		}else {
			if (noLoginPath != null && noLoginPath.length() > 0) {
				String[] noFilterPages = noLoginPath.split(";");
				for (String s : noFilterPages) {
					if (s == null || "".equals(s)) {
						continue;
					}
					// 例外的URL直接放行
					if (req.getRequestURI().indexOf(s) != -1) {
						chain.doFilter(request, response);
						return;
					}
				}
			}
			
			req.getRequestDispatcher("login.jsp").forward(request, response);	//session中没有该用户信息，又不是例外URL
		}
		
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
		noLoginPath = filterConfig.getInitParameter("noLoginPath");
	}

}
